package com.example.demo.service;


import com.example.demo.common.exception.FailedException;
import com.example.demo.common.result.FailedResult;
import com.example.demo.mapper.UserRoleDynamicSqlSupport;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.model.UserRole;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.SqlBuilder.select;

@Service
public class UserRoleService {

    private UserRoleMapper userRoleMapper;

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper){
        this.userRoleMapper = userRoleMapper;
    }

    public String selectRoleByUserID(String userID){
        SelectStatementProvider selectStatementProvider = select(UserRoleMapper.selectList)
                .from(UserRoleDynamicSqlSupport.userRole)
                .where(UserRoleDynamicSqlSupport.userid,isEqualTo(userID))
                .build().render(RenderingStrategies.MYBATIS3);
        if(userRoleMapper.selectMany(selectStatementProvider).size() == 0){
                throw new FailedException(FailedResult.USER_IS_NOT_EXIST);
        }else {
            UserRole userRole = userRoleMapper.selectMany(selectStatementProvider).get(0);
            if(userRole.getRoleid() == 1){
                return "student";
            }else {
                return "teacher";
            }
        }

    }
}
